package com.example.shop.filter;

import com.example.shop.util.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

/**
 * 过滤器
 */

//@WebFilter(urlPatterns ="/*")
public class UserFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        //1.获取请求路径
        String requestURI = req.getRequestURI();

        //2.判断是否包含login
        if (requestURI.contains("login") || requestURI.contains("register")) {
            //放行
            chain.doFilter(req, resp);
        }


        //获取token 请求头
        String token = req.getHeader("token");

        //4.判断token是否为空，为空表示未登录，返回未登录信息
        if(token == null || token.isEmpty()){
            resp.setStatus(401);
            return;
        }

        //解析token
        try {
            JwtUtils.parseJwt(token);
            //放行
            chain.doFilter(req, resp);
        } catch (Exception e) {
            //返回未登录信息
            resp.setStatus(401);
        }
    }
}
